package studio.raptor.dispatcher.scheduler;

import java.io.File;
import java.io.IOException;
import com.google.common.base.Joiner;
import org.apache.curator.test.TestingServer;
import studio.raptor.dispatcher.scheduler.exception.RegExceptionHandler;

/**
 * @author jack
 * @since 1.0
 */
public final class EmbedTestingServer {

  private static final int PORT = 3181;

  private static volatile TestingServer testingServer;

  public static String getConnectionString() {
    return Joiner.on(":").join("localhost", PORT);
  }

  public static void start() {
    if (null != testingServer) {
      return;
    }
    try {
      testingServer = new TestingServer(PORT, new File(String.format("target/test_zk_data/%s/", System.nanoTime())));
      // CHECKSTYLE:OFF
    } catch (final Exception ex) {
      // CHECKSTYLE:ON
      RegExceptionHandler.handleException(ex);
    } finally {
      Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
          try {
            testingServer.close();
          } catch (final IOException ex) {
            RegExceptionHandler.handleException(ex);
          }
        }
      });
    }
  }
}